package cn.ailearn.security.handler;

import cn.ailearn.result.Result;
import cn.ailearn.utils.web.WebUtils;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName AuthenticationEnterPointImpl
 * @Description 认证失败(异常)处理类，同一封装返回格式
 * @Author WDEMO
 * @Date 2025/10/23 16:09
 */
@Slf4j
@Component
public class AuthenticationEnterPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException, IOException {
        log.info("认证失败：{}", authException.getMessage());
        // 可以根据不同的异常类型返回不同的错误信息
        String errorMessage = "认证失败，请重新登录";
        if (authException instanceof BadCredentialsException) {
            errorMessage = "用户名或密码错误";
        } else if (authException instanceof CredentialsExpiredException) {
            errorMessage = "凭证已过期";
        }
        // 记录详细异常信息用于调试
        if (log.isDebugEnabled()) {
            log.debug("认证失败详情", authException);
        }
        Result result = Result.error(errorMessage);
        String jsonResult = JSONUtil.toJsonStr(result);
        WebUtils.writeResponse(response, jsonResult);
    }
}
